package com.util;

import java.awt.Font;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;


public class LogUtil {

	public LogUtil() {

		File dirs = new File("D:/supermarket/log");
		dirs.mkdirs();

		File file = new File("D:/supermarket/log/log.data");
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}

	public static void logList(JTabbedPane tabbedPane) {

		tabbedPane.removeAll();
		JTextArea logtext = new JTextArea();
		logtext.setFont(new Font("宋体",Font.BOLD,20));

		BufferedReader read = null;
		try {

			File file = new File("D:/supermarket/log/log.data");

			read = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));

			String buff = "";
			String log = "";
			while((buff = read.readLine()) != null) {

				log += buff+"\n\n";
			}

			logtext.setText(log+"\n");

		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {


			try {
				if(read!=null)
					read.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}



		JScrollPane scroll = new JScrollPane(logtext);
		scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		logtext.setEditable(false);

		tabbedPane.add("日志",scroll);
	}

	public static void addlog(String msg) {

		OutputStreamWriter out = null;
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String time = dateFormat.format(date);

		try {
			 out = new OutputStreamWriter(new FileOutputStream("D:/supermarket/log/log.data",true),"GBK");

			String txt = time +"    :"+msg+"\n";
			out.write(txt);
			//out.append(txt);

		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			try {
				if (out != null) {
					out.close();
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
	}
}
